//
//  LSListenTestView.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/10/23.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSListenTestView.h"
#import "KZTimeCountDownView.h"

@implementation LSListenTestView {
    
    NSTimer                     *_timer;
    CGFloat                     _second;
    BKAudioPlayer               *_player;
    CGFloat                     _playRate;
    NSInteger                   _count;//进行到第几步的计数
    BOOL                        _isCheck;//是否是查看界面
    BOOL                        _isPlaying;//是否是正在播放
    BOOL                        _isPlayEnd;//是否播放结束
    //1.预读
    UIView                      *_status1View;
    KZTimeCountDownView         *_waitTimeView; // 预读倒计时
    
    //2.播放听力
    UIView                      *_status2View;
    KZTimeCountDownView         *_voicePlayView; // 听力播放
    
    //3.作答倒计时
    UIView                      *_status3View;
    KZTimeCountDownView         *_readytoAnswerView;// 作答倒计时
    
    //5.重新作答
    UIView                      *_status4View;
    UIButton                    *_repeatBtn;
    
    //6.下一题
    UIView                      *_status5View;
    UIButton                    *_nextBtn;
    
}

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = YES;
       // [self setupUI];
        _isPlayEnd = YES;
        _isPlaying = NO;
    }
    
    return self;
}


- (void)setModel:(LSModelQues *)model {
    _model = model;
    
    _count = 0;
    
    if (self.speedLayer==1) {
        _playRate = 0.8;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
    } else if (self.speedLayer==3) {
        _playRate = 1.2;
    }
    
    [self setupUI];
}

- (void)setupUI {
    
    _player = [[BKAudioPlayer alloc] init];
    _player.delegateM = self;
    
    [self setupStatus1View];
    
    [self setupStatus2View];
    
    [self setupStatus3View];
    
    [self setupStatus4View];
    
    [self setupStatus5View];
    
}

//1.预读
- (void)setupStatus1View {
    _status1View = [UIView new];
    _status1View.userInteractionEnabled = YES;
    [self addSubview:_status1View];
    _status1View.alpha = 0;
    [_status1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _waitTimeView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypeWait withTime:_model.ReadTime+_model.WaitTime];
    [_status1View addSubview:_waitTimeView];
    [_waitTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status1View);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jumpToNext)];
    [_waitTimeView addGestureRecognizer:tap];
}

- (void)jumpToNext {
    
    [_timer invalidate];
    _timer = nil;
    
    //预读消失
    [self addHideAnimation:_status1View];
    
    //播放音频出现
    [self addFadeAnimation:_status2View];
    
    NSURL *url = nil;
    if ([_from isEqualToString:@"A00"]) {
        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.AudioList.firstObject.AudioPath]];
    } else {
        
        url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
    }
    [_player playerUrl:url seekTotime:0 rateValue:_playRate];
    _count = 2;
}

//2.播放听力
- (void)setupStatus2View {
    
    _status2View = [UIView new];
    [self addSubview:_status2View];
    _status2View.alpha = 0;
    [_status2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _voicePlayView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypePlayVoice withTime:_model.TimeLong];
    [_status2View addSubview:_voicePlayView];
    [_voicePlayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status2View);
    }];
}

//3.作答倒计时
- (void)setupStatus3View {
    _status3View = [UIView new];
    [self addSubview:_status3View];
    _status3View.alpha = 0;
    [_status3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self);
    }];
    
    _readytoAnswerView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypeReadytoAnswer withTime:_model.RecordTime];
    [_status3View addSubview:_readytoAnswerView];
    [_readytoAnswerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(80));
        make.center.equalTo(_status3View);
    }];
}

//4.重新作答
- (void)setupStatus4View {
    
    _status4View = [UIView new];
    _status4View.alpha = 0;
    [self.superview addSubview:_status4View];
    [_status4View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.superview).offset(W(46));
        make.width.height.mas_equalTo(W(64));
        make.centerY.equalTo(self);
    }];
    
    _repeatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _repeatBtn.layer.cornerRadius = W(32);
    _repeatBtn.layer.masksToBounds = true;
    _repeatBtn.layer.borderColor = KZThemeColor2.CGColor;
    _repeatBtn.layer.borderWidth = 1;
    _repeatBtn.backgroundColor = [UIColor whiteColor];
    [_repeatBtn setImage:[UIImage imageNamed:@"kz-重复"] forState:UIControlStateNormal];
    [_status4View addSubview:_repeatBtn];
    [_repeatBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status4View);
    }];
    [_repeatBtn addTarget:self action:@selector(reAnswer:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *shadowView2 = [UIView new];
    shadowView2.backgroundColor = UIColor.whiteColor;
    shadowView2.layer.cornerRadius = W(32);
    [_status4View insertSubview:shadowView2 belowSubview:_repeatBtn];
    [shadowView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_repeatBtn);
    }];
    shadowView2.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView2.layer.shadowRadius = 5;
    shadowView2.layer.shadowOpacity = 0.6;
    shadowView2.layer.shadowColor = KZThemeColor2.CGColor;
}

//5.下一题
- (void)setupStatus5View {
    _status5View = [UIView new];
    _status5View.alpha = 0;
    [self.superview addSubview:_status5View];
    [_status5View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.superview).offset(-W(46));
        make.width.height.mas_equalTo(W(64));
        make.centerY.equalTo(self);
    }];
    
    UIView *nextView = [UIView new];
    [_status5View addSubview:nextView];
    [nextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status5View);
    }];
    nextView.layer.cornerRadius = W(32);
    nextView.layer.masksToBounds = true;
    // 渐变图层
    CAGradientLayer *gradientLayer2 = [CAGradientLayer layer];
    gradientLayer2.bounds = CGRectMake(0, 0, W(64), W(64));
    gradientLayer2.position = CGPointMake(W(32), W(32));
    gradientLayer2.colors = @[
                              (__bridge id)kzRGBA(11, 175, 251, 1).CGColor,
                              (__bridge id)kzRGBA(71, 204, 255, 1).CGColor,
                              ];
    [nextView.layer insertSublayer:gradientLayer2 atIndex:0];
    
    UIView *shadowView = [UIView new];
    shadowView.backgroundColor = UIColor.whiteColor;
    shadowView.layer.cornerRadius = W(32);
    [_status5View insertSubview:shadowView belowSubview:nextView];
    [shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(nextView);
    }];
    shadowView.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView.layer.shadowRadius = 5;
    shadowView.layer.shadowOpacity = 0.6;
    shadowView.layer.shadowColor = kzRGBA(11, 175, 251, 1).CGColor;
    
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nextBtn setImage:[UIImage imageNamed:@"kz-下一个"] forState:UIControlStateNormal];
    
    [_nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [nextView addSubview:_nextBtn];
    [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(nextView);
    }];
}

#pragma mark - 交互操作
- (void)start {
    [self addFadeAnimation:_status1View];
    //开始预读
    _second = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time1Action:) userInfo:nil repeats:YES];
     [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    _count = 1;
}

- (void)reStartSpeedLayer:(NSInteger)speedLayer {
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    //需要隐藏全部的视图
    _status1View.alpha = 0;
    _status2View.alpha = 0;
    _status3View.alpha = 0;
    _status5View.alpha = 0;
    [_player closePlayer];
    
    self.speedLayer = speedLayer;
    if (self.speedLayer==1) {
        _playRate = 0.8;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
    } else if (self.speedLayer==3) {
        _playRate = 1.2;
    }
    
    [self start];
}

- (void)startSecond {
    //播放音频出现
    [self addFadeAnimation:_status2View];
    
    NSURL *url = nil;
    if ([_from isEqualToString:@"A00"]) {
        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.AudioList.firstObject.AudioPath]];
    } else {
        url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
    }
    [_player playerUrl:url seekTotime:0 rateValue:_playRate];
    _count = 2;
    [_voicePlayView.turmpetView play];
}

- (void)time1Action:(id)sender {
    _second = _second+0.1;
    //NSLog(@"%lf",_second);
    _waitTimeView.time = _second;
    if (_second >= _model.WaitTime+_model.ReadTime) {
        
        [_timer invalidate];
        _timer = nil;
        
        //预读消失
        [self addHideAnimation:_status1View];
        
        //播放音频出现
        [self addFadeAnimation:_status2View];
        
        NSURL *url = nil;
        if ([_from isEqualToString:@"A00"]) {
            url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.AudioList.firstObject.AudioPath]];
        } else {
            
            url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
        }
        [_player playerUrl:url seekTotime:0 rateValue:_playRate];
        _count = 2;
    }
}


#pragma mark - BKAudioDelegate
- (void)audioUpdateWith:(float)time Totaltime:(float)totalTime {
    _voicePlayView.totalTime = totalTime;
    _voicePlayView.time = time;
    _isPlayEnd = NO;
}

- (void)audioPlayEnd {
    
    _isPlayEnd = YES;
    
    [_player closePlayer];
    //喇叭暂停
    [_voicePlayView.turmpetView stop];
    
    if(_isCheck)  {
        [_voicePlayView reset];
        return;
    }
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    //播放消失
     [self addHideAnimation:_status2View];
    //作答倒计时出现
     [self addFadeAnimation:_status3View];
    
    _second = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time2Action:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    _count = 3;
}

- (void)time2Action:(id)sender {
    _second = _second+0.1;
    _readytoAnswerView.time = _second;
    if (_second>=_model.RecordTime) {
        
        [_timer invalidate];
        _timer = nil;
        //倒计时消失
        [self addHideAnimation:_status3View];
        
        //时间结束
        if (self.delegate && [self.delegate respondsToSelector:@selector(LSListenTestViewEnd)]) {
            [self.delegate LSListenTestViewEnd];
        }
       
    }
}

//4. 重新作答/下一题按钮
- (void)showNextAndReAnswer {
     [self addFadeAnimation:_status4View];
     [self addFadeAnimation:_status5View];
}

- (void)showNext {
    [_status5View mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.superview).offset(-(kWidth - W(64))/2);
    }];
    [self addFadeAnimation:_status5View];
}

#pragma mark - 动画
//显示动画
- (void)addFadeAnimation:(UIView*)view {
    
    CABasicAnimation * fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnim.fromValue = @(0);
    fadeAnim.toValue = @(1);
    fadeAnim.repeatCount = 1;
    fadeAnim.duration = 0.5;
    //以下两行同时设置才能保持移动后的位置状态不变
//    fadeAnim.fillMode=kCAFillModeForwards;
//    fadeAnim.removedOnCompletion = NO;
    [view.layer addAnimation:fadeAnim forKey:@"Fade"];
    view.alpha = 1;
}

//消失动画
- (void)addHideAnimation:(UIView*)view {
    
    if (view == _status2View) {
        [_voicePlayView reset];
    } else if (view == _status3View) {
        [_readytoAnswerView reset];
    }
    
    CABasicAnimation * fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnim.fromValue = @(1);
    fadeAnim.toValue = @(0);
    fadeAnim.repeatCount = 1;
    fadeAnim.duration = 0.5;
    //以下两行同时设置才能保持移动后的位置状态不变
//    fadeAnim.fillMode=kCAFillModeForwards;
//    fadeAnim.removedOnCompletion = NO;
    [view.layer addAnimation:fadeAnim forKey:@"Hide"];
    view.alpha = 0;
}

#pragma mark - 按钮点击事件
- (void)reAnswer:(id)sender {
    [self addHideAnimation:_status4View];
    [self addHideAnimation:_status5View];
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSListenReAnswer)]) {
        [self.delegate LSListenReAnswer];
    }
}

- (void)nextAction:(id)sender {
//    [self addHideAnimation:_status4View];
//    [self addHideAnimation:_status5View];
    if (self.delegate && [self.delegate respondsToSelector:@selector(LSListenNext)]) {
        [self.delegate LSListenNext];
    }
}

#pragma mark - 定时器取消和暂停、重启
- (void)pause {
    [_timer setFireDate:[NSDate distantFuture]];
    if (_player.player) {
        [_player playerPaused];
        [_voicePlayView.turmpetView pause];
         _isPlaying = NO;
    }
}

- (void)resume {
    [_timer setFireDate:[NSDate distantPast]];
    if (_player.player) {
        [_player playerPlay];
        [_voicePlayView.turmpetView resume];
        _isPlaying = YES;
    }
}

- (void)stop {
    [_timer invalidate];
    _timer = nil;
    
    [_player closePlayer];
    [_voicePlayView.turmpetView stop];
    
    //消失
    if (_count==1) {
        //[self addHideAnimation:_status1View];
        _status1View.alpha = 0;
    }
    if (_count==2) {
       // [self addHideAnimation:_status2View];
        _status2View.alpha = 0;
    }
    if (_count==3) {
       // [self addHideAnimation:_status3View];
        _status3View.alpha = 0;
    }
}

- (void)showPlayerVoice {
    _status2View.alpha = 1;
    [_voicePlayView.turmpetView pause];
    _isCheck = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playOrPause:)];
    [_status2View addGestureRecognizer:tap];
    
}

- (void)playOrPause:(id)sender {
    if (_isPlayEnd) {
        NSURL *url = nil;
        if ([_from isEqualToString:@"A00"]) {
            url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.AudioList.firstObject.AudioPath]];
        } else {
            
            url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
        }
        NSLog(@"url=%@",url);
        [_player playerUrl:url seekTotime:0 rateValue:_playRate];
        [_voicePlayView.turmpetView play];
         _isPlaying = YES;
        
    } else {
        
        if (_isPlaying) {
            [_player playerPaused];
            [_voicePlayView.turmpetView pause];
            _isPlaying = NO;
        } else {
            [_player playerPlay];
            [_voicePlayView.turmpetView resume];
            _isPlaying = YES;
        }
        
    }
}

@end
